package com.syni.mdd.yhd.common.all.service.order.impl;

import com.alibaba.fastjson.JSON;
import com.syni.mdd.sjb.common.component.utils.common.utils.ArithUtil;
import com.syni.mdd.sjb.common.component.utils.common.utils.DateTimeUtils;
import com.syni.mdd.sjb.common.component.utils.common.utils.ParamsMap;
import com.syni.mdd.sjb.common.component.utils.common.utils.ResultMapHelper;
import com.syni.mdd.yhd.common.all.constants.Constants;
import com.syni.mdd.yhd.common.all.constants.ResultCode;
import com.syni.mdd.yhd.common.all.constants.ResultMsg;
import com.syni.mdd.yhd.common.all.entity.BmsDxGroupBuy;
import com.syni.mdd.yhd.common.all.entity.BmsDxOrder;
import com.syni.mdd.yhd.common.all.entity.groupBuy.BmsThirdCode;
import com.syni.mdd.yhd.common.all.entity.order.OrderCommitHolder;
import com.syni.mdd.yhd.common.all.entity.platformGood.BmsPlatformGood;
import com.syni.mdd.yhd.common.all.enums.ActivityEnums;
import com.syni.mdd.yhd.common.all.enums.platformGood.PlatformGoodEnum;
import com.syni.mdd.yhd.common.all.service.*;
import com.syni.mdd.yhd.common.all.service.order.OrderCommitService;
import com.syni.mdd.yhd.common.all.service.platformGoods.BmsPlatformGoodService;
import com.syni.mdd.sjb.common.component.utils.common.utils.ArithUtil;
import com.syni.mdd.yhd.common.all.utils.RequestParamUtils;
import com.syni.mdd.yhd.common.all.utils.WebUtils;
import com.syni.mdd.sjb.common.component.utils.feign.dto.mddDistSys.OrderSubmitDto;
import com.syni.mdd.sjb.common.component.utils.redis.utils.RedisTemplateUtils;;
import com.syni.mdd.sjb.common.component.utils.feign.service.mddDistSys.FxCenterService;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.persistence.EntityManager;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @className PlatformOrderServiceImpl
 * @description TOO
 * @Author cfx
 * @DATE 2020/3/13 22:34
 * @VERSION 1.0
 **/
@Component
public class FenXiaoOrderServiceImpl implements OrderCommitService {
    @Autowired
    BmsPlatformGoodService bmsPlatformGoodService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    BmsDxOrderService bmsDxOrderService;
    @Autowired
    BmsDxGroupBuyService bmsDxGroupBuyService;
    @Autowired
    BmsThirdCodeService bmsThirdCodeService;
    @Autowired
    BmsDxGroupBuyUseService bmsDxGroupBuyUseService;
    @Autowired
    FxCenterService fxCenterService;

    @Autowired
    EntityManager entityManager;
    @Override
    public OrderCommitHolder commitLogic(OrderCommitHolder orderCommitHolder) {
        ParamsMap paramsMap = orderCommitHolder.getParamsMap();
        BmsDxOrder bmsDxOrder = orderCommitHolder.getBmsDxOrder();

        Date nowTime = new Date();
        Integer businessId = paramsMap.getInteger("businessId");
        List<BmsThirdCode> bmsThirdCodes = null;
        String userIdentify = paramsMap.get("userIdentify").toString();
        Integer userId = Integer.parseInt(userIdentify);
        Integer reId = paramsMap.getInteger("reId");

        Map<String, Object> checkMap = RequestParamUtils.checkParams(paramsMap, "groupBuyNum", "groupBuyId");
        if (!(checkMap.containsKey("status") && ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString()))) {
            orderCommitHolder.getExecutionResult().putAll(checkMap);
            return orderCommitHolder;
        }
        Integer groupBuyId = Integer.parseInt(paramsMap.get("groupBuyId").toString());
        Integer groupBuyNum = Integer.parseInt(paramsMap.get("groupBuyNum").toString());

        BmsDxGroupBuy bmsDxGroupBuy = bmsDxGroupBuyService.getGroupBuyById(groupBuyId);
        if (bmsDxGroupBuy == null) {
            orderCommitHolder.getExecutionResult().putAll(ResultMapHelper.result(ResultCode.CODE_BUSINESS_NO_EXIST_GROUP_BUY, ResultMsg.CODE_BUSINESS_NO_EXIST_GROUP_BUY));
            return orderCommitHolder;
        }
        bmsDxOrder.setBmsDxGroupBuy(bmsDxGroupBuy);
        if(bmsDxGroupBuy.getLeastBuyNum() != null && bmsDxGroupBuy.getLeastBuyNum() > 0) {
            if(groupBuyNum < bmsDxGroupBuy.getLeastBuyNum()){
                orderCommitHolder.getExecutionResult().putAll(ResultMapHelper.result(ResultCode.CODE_ERROR_100, ResultMsg.MSG_LEAST_BUY_NUM));
                return orderCommitHolder;
            }
        }
        if (!(bmsDxGroupBuy.getStatus() == Constants.COMMON_FLAG_TRUE_INT)) {
            orderCommitHolder.getExecutionResult().putAll(ResultMapHelper.result(ResultCode.CODE_BUSINESS_GROUOP_AL_OFFLINE, ResultMsg.CODE_BUSINESS_GROUOP_AL_OFFLINE));
            return orderCommitHolder;
        }
        //判断该团购是否过期
        if (bmsDxGroupBuy.getExpireTime() != null) {
            Date overTime = DateTimeUtils.addDay(bmsDxGroupBuy.getExpireTime(), 1);
            if (nowTime.getTime() >= overTime.getTime()) {
                orderCommitHolder.getExecutionResult().putAll(ResultMapHelper.result(ResultCode.CODE_BUSINESS_GROUP_EXPIRE, ResultMsg.CODE_BUSINESS_GROUP_EXPIRE));
                return orderCommitHolder;
            }
        }
        //判断是否是特特乐团购，需要锁库存
        if (bmsDxGroupBuy.getGroupType() != null && bmsDxGroupBuy.getGroupType() == Constants.GROUP_TYPE_TETE) {
            //判断是否到抢购时间
            if (bmsDxGroupBuy.getStartSellTime() != null) {
                if (DateTimeUtils.converDateToInterger(nowTime) < DateTimeUtils.converDateToInterger(bmsDxGroupBuy.getStartSellTime())) {
                    orderCommitHolder.getExecutionResult().putAll(ResultMapHelper.result(ResultCode.CODE_GROUP_NO_CAN_BUY, ResultMsg.CODE_GROUP_NO_CAN_BUY));
                    return orderCommitHolder;
                }
            }
            //判断抢购时间是否过期
            if (bmsDxGroupBuy.getLimitBuyTime() != null) {
                if (DateTimeUtils.converDateToInterger(nowTime) >= DateTimeUtils.converDateToInterger(bmsDxGroupBuy.getLimitBuyTime())) {
                    orderCommitHolder.getExecutionResult().putAll(ResultMapHelper.result(ResultCode.CODE_BUSINESS_GROUP_EXPIRE, ResultMsg.CODE_BUSINESS_GROUP_EXPIRE));
                    return orderCommitHolder;
                }
            }
            //锁当前团购套餐的库存
            bmsThirdCodes = bmsThirdCodeService.checkUseCodeHavingUseNum(businessId, groupBuyId, groupBuyNum);
            if (!(bmsThirdCodes != null && bmsThirdCodes.size() == groupBuyNum)) {
                //库存不足，下架团购
                orderCommitHolder.getExecutionResult().putAll(ResultMapHelper.result(ResultCode.CODE_BUSINESS_NOT_ENOUGH, ResultMsg.CODE_BUSINESS_NOT_ENOUGH));
                return orderCommitHolder;
            }
        }
        if(bmsDxGroupBuy.getIsTimeLimit() != null && bmsDxGroupBuy.getIsTimeLimit() == Constants.COMMON_FLAG_TRUE_INT){
            Date startSellTime = bmsDxGroupBuy.getStartSellTime();
            Date limitBuyTime = bmsDxGroupBuy.getLimitBuyTime();
            if(startSellTime != null && DateTimeUtils.match(nowTime,startSellTime,DateTimeUtils.MATCH_MODEL_LT)){
                orderCommitHolder.getExecutionResult().putAll(ResultMapHelper.result(ResultCode.CODE_ERROR_100, ResultMsg.MSG_NOT_TIME_FOR_SALE));
                return orderCommitHolder;
            }
            if(limitBuyTime != null && DateTimeUtils.match(nowTime,limitBuyTime,DateTimeUtils.MATCH_MODEL_GT)){
                orderCommitHolder.getExecutionResult().putAll(ResultMapHelper.result(ResultCode.CODE_ERROR_100, ResultMsg.MSG_BUY_TIME_OVER));
                return orderCommitHolder;
            }
        }
        //是否超过团购券限制购买数量
        if (bmsDxGroupBuy.getLimitBuyNum() != null) {
            //查询当前用户已经买了多少张这个团购券
            Integer userAlreadyBuyNum = bmsDxGroupBuyUseService.getUserBuyNum(userId, bmsDxGroupBuy.getId());
            if (groupBuyNum > (bmsDxGroupBuy.getLimitBuyNum() - userAlreadyBuyNum)) {
                orderCommitHolder.getExecutionResult().putAll(ResultMapHelper.result(ResultCode.CODE_BUSINESS_OVER_NUM, ResultMsg.CODE_BUSINESS_OVER_NUM));
                return orderCommitHolder;
            }
        }
        if (bmsDxGroupBuy.getSellInventory() != null) {
            String redisKey = Constants.REDIS_KEY_BUINESS_GROUP_BUY + bmsDxGroupBuy.getId();
            boolean addLockResult = RedisTemplateUtils.addLock(redisKey, RedisTemplateUtils.GEN_TRY_NUM);
            if (!addLockResult) {
                orderCommitHolder.getExecutionResult().putAll(ResultMapHelper.result(ResultCode.CODE_ORDER_PLACE_FAIL, ResultMsg.CODE_ORDER_PLACE_FAIL));
                return orderCommitHolder;
            }
            paramsMap.put("isAddLock", redisKey);
            Integer num = bmsDxGroupBuyService.getBaseDao().countGroupBuySellNum(groupBuyId);
            if (groupBuyNum > num) {
                orderCommitHolder.getExecutionResult().putAll(ResultMapHelper.result(ResultCode.CODE_BUSINESS_NOT_ENOUGH, ResultMsg.CODE_BUSINESS_NOT_ENOUGH));
                return orderCommitHolder;
            }
            bmsDxGroupBuy.setSellInventory(num - groupBuyNum);
        }
        Double totalConsum = ArithUtil.mul(groupBuyNum, bmsDxGroupBuy.getGroupPrice());
        Double actualConsum = totalConsum;
        bmsDxOrder.setBmsGroupBuyId(bmsDxGroupBuy.getId());
        bmsDxOrder.setGroupBuyNum(groupBuyNum);
        bmsDxOrder.setTotalConsum(totalConsum);
        bmsDxOrder.setActualConsum(actualConsum);
        if(reId != null) {
            Map<String, Object> shopList = new HashMap<>();
            shopList.put("reId", reId);
            bmsDxOrder.setRemark(JSON.toJSONString(shopList));
        }
        orderCommitHolder.getExecutionResult().putAll(ResultMapHelper.success());
        return orderCommitHolder;
    }
}
